<div id="timeBoardPage">
	<div class="pageContent" style="border-bottom: 1px solid #D9DFE5;">
		<div style="border-top: 1px solid #D9DFE5;" id="jGridForTimeBoard"></div>
	</div>
	<div class="pageContent" style="margin-top: 3px;" id="jGridForTimeBoardDetail"></div>
</div>
<style>
#jGridForTimeBoard .timeLen {
	height: 16px;
	line-height: 16px;
	text-align: center;
	background: #2EC7C9;
	top: 50%;
	margin-top: -8px;
	cursor: pointer;
	moz-user-select: -moz-none;
	-moz-user-select: none;
	-o-user-select:none;
	-khtml-user-select:none;
	-webkit-user-select:none;
	-ms-user-select:none;
	user-select:none;
	float: left;
	min-width: 1px;
}
#jGridForTimeBoard .timeText {
	height: 21px;
	line-height: 21px;
	margin-left: 2px;
	color: #888;
}
#jGridForTimeBoard tbody tr {
	height: 30px;
}
#jGridForTimeBoard tbody tr td {
	border-bottom: 1px solid #F2F2F2;
}
</style>
<script>
(function($){
	var $page = DWZ.context(), 
	
	$grid = $('#jGridForTimeBoard', $page),
	
	$detailGrid = $('#jGridForTimeBoardDetail', $page),
	
	scheduleDays = 7,
	
	dateFmt = 'yyyy-MM-dd', timeFmt = 'yyyy-MM-dd HH:mm:ss',
	perDay = 24 * 60 * 60 * 1000,
	currentDate = new Date(), currentDay = currentDate.getDay(),
	
	daysOfWeek = new Array("<@label key='sunday.C'>星期日</@label>", "<@label key='Mon.C'>星期一</@label>", "<@label key='Tues.C'>星期二</@label>", "<@label key='Wed.C'>星期三</@label>",
		"<@label key='Thur.C'>星期四</@label>", "<@label key='Fri.C'>星期五</@label>", "<@label key='Sat.C'>星期六</@label>"),
	
	tableWidth = 340,
	
	startDate = new Date(), endDate = new Date(), maxDate, start = '', end = '';
	// 默认时间范围上一周
	startDate.setTime(currentDate.getTime() - 6 * perDay);
	start = startDate.formatDate(dateFmt);
	end = endDate.formatDate(dateFmt);
	
	var getColumns = function(start, end) {
		var columns = [
			{field: '_index', text: '<@label key="serialNumber.C">序号</@label>', width: 40},
			{field: 'PERSONNELCODE', text: '人员编号', width: 100, orderTable: 's'},
			{field: 'PERSONNELNAME', text: '姓名', width: 120},
			{field: 'count', text: '小计（时）', width: 80}
		];
		
		tableWidth = 340;
		
		for (var int = 0; int < scheduleDays; int++) {
			var column = {};
			column.field = start.formatDate(dateFmt);
			column.title = start.formatDate(dateFmt) + ' ' + daysOfWeek[start.getDay()];
			column.text = daysOfWeek[start.getDay()];
			column.width = 100;
			column.thrender = function(th){
				th.css({'text-align': 'center'});
			};
			tableWidth += column.width;
			columns.push(column);
			start.setTime(start.getTime() + perDay);
			if (start.getTime() > end.getTime()) {
				break;
			}
		}
		// 如果总宽度小于div宽度，则设置为div宽度，列宽自适应
		if (tableWidth < $grid.width()) {
			tableWidth = 0;
		}
		return columns;
	};
	
	var columns = getColumns(startDate, endDate);
	
	$grid.jGrid({
		height: 220,
		layoutH: 97,
		gridHeaderHeight: 51,
		base: hostUrl + '/timeBoard/',
		url: 'getPerformances',
		autoLoad: false,
		width: tableWidth,
		lockColumnNum: 4,
		columns: columns,
		orderable: false,
		trselectable: false,
		pageable: false,
		query: {
			queryfields: [
				{field: 'workCenterCode', text: '工作中心', type: 'select', options: [
					{value: '', label: '<@label key="all.C">所有</@label>'},
					<#list permissions as permission>
					{value: '${permission.workcenterCode}', label: '${permission.workcenterText}'},
					</#list>
				]},
				{field: 'minTheDate', type: 'date', text: '日期', format: dateFmt, css: 'from', dateGroup: 'theDate', value: start, required: true},
				{field: 'maxTheDate', type: 'date', text: '到', format: dateFmt, css: 'to', dateGroup: 'theDate', value: end, required: true}
			]
		},
		gridbars: [
			/*{icon: 'export', text: '<@label key="exportToExcel.D">导出</@label>', title: '<@label key="confirmexportToExcel.M"></@label>', 
				target: 'export', href: '', data: {navTabId: "${navTabId!''}"}, mask: true, width: 950, height: 450, 
				menuCode: 'undefined'}*/
		]
	});
	
	$detailGrid.hide().jGrid({
		layoutH: 380,
		width: 1300,
		base: hostUrl + '/timeBoard/',
		url: 'getPerformanceBypersonnelAndPeriod',
		autoLoad: false,
		columns: [
			{field: '_index', text: '<@label key="serialNumber.C">序号</@label>', width: 40},
			{field:'personnelCode', text:'<@label key="personnelCode.C">人员编号</@label>', width: 100},
			{field:'personnelName', text:'<@label key="personnelName.C">人员姓名</@label>', width: 100},
			{field:'workcenterText', text:'<@label key="workCenter.C">工作中心</@label>', width: 100},
			{field:'shiftingWorkcenterText', text:'<@label key="shiftingWorkCenter.C">实际工作中心</@label>', width: 100},
			{field:'theDate', type: 'date', format: dateFmt, text:'<@label key="date.C">日期</@label>', width: 100},
			{field:'startDatetime', type: 'date', format: timeFmt, text:'<@label key="startTime.C">开始时间</@label>', width: 120},
			{field:'endDatetime', type: 'date', format: timeFmt, text:'<@label key="endTime.C">结束时间</@label>', width: 120},
			{field:'materialCode', text:'<@label key="materialCode.C">物料编号</@label>', width: 100},
			{field:'materialText', text:'<@label key="materialText.C">物料描述</@label>', width: 100},
			{field:'quantity', text:'<@label key="quantity.C">数量</@label>', width: 80},
			{field:'memo', text:'<@label key="memo.C">备注</@label>', width: 100}
		],
		gridbars: [
			{icon: 'open', text: '展开列表', title: '展开列表', target: 'action', action: function() {
				expandDetailGrid();
			}}
		],
		orderable: false,
		trselectable: false,
		pageable: false
	});
	
	var $cosIcon = $('<li class="" style="float: right;"><a target="" href="javascript:void(0);" class="expand"><span></span></a></li>')
	.appendTo($('<ul class="toolBar"/>').appendTo($('.panelBar', $detailGrid))).on('click', function(){
		toggleGrid(true);
	}),
	
	$form = $('form:first', $page), $start = $('[name=minTheDate]', $form), $end = $('[name=maxTheDate]', $form),
	
	displayColumnsLabel = function(columns) {
		var $table = $('.gridTbody table', $grid), $tbody = $('>tbody', $table), 
		$tr = $('<tr/>'), $thead = $('.gridHeader', $grid).height(51).find('thead'),
		trFirst = $('tr:first', $thead);
		
		for (var cIndex = 0; cIndex < columns.length; cIndex++) {
			if (cIndex > 3) {
				$('<div style="text-align: center;" class="gridCol"/>').append(columns[cIndex].field).appendTo($('th:eq(' + cIndex + ')', trFirst));
			}
		}
	};
	
	$start.on('change', function(){
		if (this.value) {
			var start = this.value.parseDate(dateFmt);
			maxDate = new Date(start.getTime());
			maxDate.setMonth(start.getMonth() + 1);
			maxDate.setDate(0);
			scheduleDays = maxDate.getDate();
			$end.attr('maxDate', new Date(start.getTime() + (scheduleDays - 1) * perDay).formatDate(dateFmt));
			var end = $end.val();
			if (end && end.parseDate(dateFmt).getTime() > $end.attr('maxDate').parseDate(dateFmt).getTime()) {
				$end.val($end.attr('maxDate'));
			}
		}
	});
	
	displayColumnsLabel(columns);
	
	var toggleGrid = function(isDisplay) {
		var $gridPart = $('.gridPart', $grid), $tbody = $('.gridBody', $gridPart);
		if (isDisplay) {
			resizeDetailGrid();
			$grid.parent().slideDown('fast');
			$gridPart.animate({height: $page.height() - 46}, 'fast', function(){
				$gridPart.attr({layoutH: 46});
				$tbody.attr({layoutH: 97});
				$detailGrid.hide();
				$(window).resize();
			});
		} else {
			$gridPart.removeAttr('layoutH').animate({height: 271}, 'fast', function(){
				$tbody.removeAttr('layoutH').height(204);
				$('.gridScrollerBar>div', $detailGrid).height(1);
				$detailGrid.fadeIn(20);
			});
		}
	},
	
	expandDetailGrid = function() {
		var $p = $grid.parent(), $gridPart = $('.gridPart', $detailGrid), $tbody = $('.gridBody', $detailGrid);
		$p.slideUp('falst', function(){
			$detailGrid.css('margin-top', '-1px');
		});
		$gridPart.attr({layoutH: 32});
		$tbody.attr({layoutH: 76});
		$(window).resize();
	},
	
	resizeDetailGrid = function() {
		var $gridPart = $('.gridPart', $detailGrid), $tbody = $('.gridBody', $detailGrid);
		$detailGrid.css('margin-top', '3px');
		$gridPart.attr({layoutH: 353});
		$tbody.attr({layoutH: 396});
		$(window).resize();
	},
	
	$temp = $('<div/>').addClass('timeLen'),
	
	$text = $('<span/>').addClass('timeText'),
	
	fields = ['PERSONNELCODE', 'PERSONNELNAME', 'WORKHOURS'],
	
	resizeColumnWidth = function($timeL) {
		if ($timeL.width() > $timeL.parents('td:first').width() - 20) {
			var $td = $('tbody>tr:first>td[columnField=' + $timeL.parents('td:first').attr('columnField') + ']', $grid),
			$th = $('thead>tr:first>th[orderField=' + $timeL.parents('td:first').attr('columnField') + ']', $grid),
			originalWidth = $td.width(), $bar = $('.gridScrollerBar>div', $grid);
			$td.css({
				width: $timeL.width() + 20
			});
			$th.css({
				width: $timeL.width() + 20
			});
			$bar.width($bar.width() + $td.width() - originalWidth);
		}
	},
	
	loadDetail = function (personnelCode, theDate) {
		$detailGrid.jGrid('loadData', {
			personnelCode: personnelCode,
			minTheDate: theDate, 
			maxTheDate: theDate
		});
		toggleGrid(false);
	},
	
	postDate = {};
	
	$('.searchContent .query button').off('click').on('click', function(){
		if ($form.valid()) {
			var startDate = $start.val().parseDate(dateFmt), 
			endDate = $end.val().parseDate(dateFmt);
			$('.gridScrollerBar', $grid).scrollLeft(0);
			var _columns = getColumns(startDate, endDate);
			$grid.jGrid('option', {columns: _columns, width: tableWidth});
			displayColumnsLabel(_columns);
			postDate.minTheDate = $start.val();
			postDate.maxTheDate = $end.val();
			DWZ.ajax({
				url: hostUrl + '/timeBoard/getPerformances',
				data: $.extend({}, postDate, {workCenterCode: $('[name=workCenterCode]', $form)[0].value}),
				success: function(list) {
					if (list && list.length) {
						var personnels = new Array();
						$.each(list, function(){
							if (personnels.indexOf(this[fields[0]]) == -1) {
								personnels.push(this[fields[0]]);
								$grid.jGrid('appendRow');
								var personnelCode = this[fields[0]], personnelName = this[fields[1]], theDate = new Date(this.THEDATE).formatDate(dateFmt);
								var $tr = $('tbody > tr:last', $grid).attr('personnelCode', personnelCode),
								$cell = $('>td[columnField=' + theDate + ']>div', $tr)
								.append($temp.clone().width(5 * (this[fields[2]] || 0)).on('click', function(){
									loadDetail(personnelCode, theDate);
									return false;
								})).append($text.clone().text(this[fields[2]]).on('click', function() {
									loadDetail(personnelCode, theDate);
									return false;
								}));
								$('>td:eq(1)>div', $tr).text(personnelCode);
								$('>td:eq(2)>div', $tr).text(personnelName);
								$('>td:eq(3)>div', $tr).append($('<a style="height: 25px; line-height: 25px; float: left; color: #3636CC; cursor: pointer; text-decoration: underline;" href="javascript:void(0);"/>').text(this[fields[2]]).on('click', function(){
									$detailGrid.jGrid('loadData', $.extend({}, postDate, {personnelCode: personnelCode}));
									toggleGrid(false);
									return false;
								}));
								resizeColumnWidth($('>.timeLen', $cell));
							} else {
								var $tr = $('tbody > tr[personnelCode=' + this[fields[0]] + ']', $grid),
								$cell = $('>td[columnField=' + new Date(this.THEDATE).formatDate(dateFmt) + ']>div', $tr),
								$timeL = $('>.timeLen', $cell), personnelCode = this[fields[0]], theDate = new Date(this.THEDATE).formatDate(dateFmt);
								if (!$timeL.length) {
									$timeL = $temp.clone().width(0).on('click', function(){
										loadDetail(personnelCode, theDate);
										return false;
									}).appendTo($cell);
									$text.clone().text(0).on('click', function(){
										loadDetail(personnelCode, theDate);
										return false;
									}).appendTo($cell);
								}
								$timeL.width($timeL.width() + 5 * (this[fields[2]] || 0));
								resizeColumnWidth($timeL);
								$timeL.next().text(parseFloat($timeL.next().text()) + this[fields[2]]);
								var $count = $('>td:eq(3)>div>a', $tr);
								if (!$count.text()) {
									$count.text(0);
								}
								$count.text(parseFloat($count.text()) + this[fields[2]]);
							}
						});
					} else {
						$grid.jGrid('clearData');
					}
				},
				error: function() {
					$grid.jGrid('clearData');
				}
			});
		}
		return false;
	});
})(jQuery);
</script>